package com.charles.video.auth.service;

import com.charles.video.api.domain.SysMember;
import com.charles.video.api.feignService.RemoteMemberService;
import com.charles.video.api.model.MemberLogin;
import com.charles.video.common.core.constant.SecurityConstants;
import com.charles.video.common.core.exception.ServiceException;
import com.charles.video.common.core.responseDomain.R;
import com.charles.video.common.core.utils.BcryptUtils;
import com.charles.video.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Charles-H
 * <p>
 * 登录校验
 */
@Component
public class SysLoginService {

    @Autowired
    private RemoteMemberService remoteMemberService;

    public MemberLogin login(String memberNum, String password) {
        if (StringUtils.isAnyBlank(memberNum, password)) {
            throw new ServiceException("请输入工号或密码");
        }

        // 远程调用服务，获取成员信息
        R<MemberLogin> res = remoteMemberService.getMemberInfo(memberNum, SecurityConstants.INNER);

        if (R.FAIL == res.getCode()) {
            throw new ServiceException(res.getMsg());
        }

        MemberLogin memberLogin = res.getData();
        SysMember memberInfo = memberLogin.getMember();

        if (!memberInfo.getRole().equals("超级管理员") && !memberInfo.getRole().equals("普通管理员")) {
            throw new ServiceException("无权访问");
        }

        if (!BcryptUtils.checkPassword(password, memberInfo.getPassword())) {
            throw new ServiceException("工号或密码错误");
        }

        remoteMemberService.recordLoginTime(memberInfo, SecurityConstants.INNER);
        return memberLogin;
    }

}
